﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZRFCore.MotionControlCard;
using ZRFCore.MotionControlCard.Zmc;
using ZRFCore.Tool;

namespace MultiAxisVisionAssembly.Motion
{
    public class Machine
    {
        protected IMotion motion;//运动卡对象
        protected IAxis xAxis;//X轴
        protected IAxis yAxis;//Y轴
        protected IAxis zAxis;//Z轴
        protected IInterpolation interpolation;//插补对象
        /// <summary>
        /// 初始化完成
        /// </summary>
        public bool IsInitialized { get; private set; }

        private bool allHomingMark = false;//正在回零标记

        public MotionStatus MotionStatus
        {
            get
            {
                return motion.MotionStatus;
            }
        }

        public Machine()
        {
            motion = new ZmcMotion();
            xAxis = new ZmcAxis(new IntPtr(), new AxisInitType());
            yAxis = new ZmcAxis(new IntPtr(), new AxisInitType());
            zAxis = new ZmcAxis(new IntPtr(), new AxisInitType());
            interpolation = new ZmcInterpolation(new IntPtr(), Array.Empty<int>());
            IsInitialized = false;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns>返回初始化的结果  true：初始化成功</returns>
        public void Init()
        {
            try
            {
                bool connt = motion.ConnectEtherCat("192.168.0.11");
                if (!connt)
                {
                    //motionEnable = false;
                    //System.Environment.Exit(1);//退出系统
                    throw new Exception("运动卡连接失败！");
                }

                //IO初始化
                motion.InitAllIO(36, 12);

                //轴初始化
                motion.InitAllAxis(new AxisInitType[]{
                                                        new AxisInitType(){AxisIndex = 0,AxisType = AxisType.StepperMotor,Brand = new  Brand_LeadShine()},
                                                         new AxisInitType(){AxisIndex = 1,AxisType = AxisType.StepperMotor,Brand = new  Brand_LeadShine()},
                                                          new AxisInitType(){AxisIndex = 2,AxisType = AxisType.StepperMotor,Brand = new  Brand_LeadShine()},
                                                     });//XYZR
                xAxis = motion.AxisList[0];//接收轴对象
                yAxis = motion.AxisList[1];//接收轴对象
                zAxis = motion.AxisList[2];//接收轴对象
                xAxis.Invert = false;
                yAxis.Invert = false;
                zAxis.Invert = false;
                xAxis.AxisBaseIn = 0;
                yAxis.AxisBaseIn = 1;
                zAxis.AxisBaseIn = 2;

                //软限位
                xAxis.AxisSoftPositiveLimit = 320;
                xAxis.AxisSoftNegativeLimit = -1;

                yAxis.AxisSoftPositiveLimit = 270;
                yAxis.AxisSoftNegativeLimit = -1;

                zAxis.AxisSoftPositiveLimit = 92.8f;
                zAxis.AxisSoftNegativeLimit = -1;


                //脉冲当量设置 （每单位脉冲数）
                xAxis.Units = 500;
                yAxis.Units = 500;
                zAxis.Units = 64.1025641f;

                //复位爬行速度
                xAxis.HomingCreep = 10;
                yAxis.HomingCreep = 10;
                zAxis.HomingCreep = 10;
                //最大速度(按设置过当量计算)
                MaxSpeed = 200;
                Speed = 50;

                //插补初始化
                motion.InitAllInterpolation(new List<int[]> { new int[] { 0, 1, 2, } });
                interpolation = motion.InterpolationList[0];
                interpolation.DecelAngle = 15;
                interpolation.StopAngle = 30;
                IsInitialized = true;
            }
            catch
            {
                throw;
            }
        }

        #region IO

        public IInput In_OutStartSignal { get { return motion.InputList[17]; } }//外部启动信号

        public IInput In_StartButton { get { return motion.InputList[18]; } }//开始按钮

        public IInput In_ResetButton { get { return motion.InputList[19]; } }//复位按钮

        public IInput In_EmergentStopButton { get { return motion.InputList[20]; } }//急停按钮

        public IOutput Out_GlueControl { get { return motion.OutputList[0]; } }//出胶输出

        public IOutput Out_PointGlueControl { get { return motion.OutputList[2]; } }

        public IOutput Out_GlueFinish { get { return motion.OutputList[10]; } }//出胶完成信号

        public IOutput Out_GlueChangeToSmall { get { return motion.OutputList[1]; } }//切换成小胶头点胶

        #endregion

        #region 轴

        public IAxis XAxis { get { return xAxis; } }
        public IAxis YAxis { get { return yAxis; } }
        public IAxis ZAxis { get { return zAxis; } }


        /// <summary>
        /// 速度百分比。value = 50 ，即50%
        /// </summary>
        public float SpeedPercent
        {
            get
            {
                return Speed / MaxSpeed * 100;
            }
            set
            {
                if (value > 100)
                {
                    value = 100;
                }
                if (value < 0)
                {
                    value = 1;
                }
                Speed = (float)MaxSpeed * value / 100;
                Accel = (float)MaxSpeed * value / 10;
                Decel = (float)MaxSpeed * value / 10;
            }
        }

        public float MaxSpeed { get; set; }

        public float Speed
        {
            get
            {
                return xAxis.Speed;
            }
            set
            {
                if (value > MaxSpeed)
                {
                    xAxis.Speed = MaxSpeed;
                    yAxis.Speed = MaxSpeed;
                    zAxis.Speed = MaxSpeed;
                }
                else
                {
                    xAxis.Speed = value;
                    yAxis.Speed = value;
                    zAxis.Speed = value;
                }
            }
        }

        public float Accel
        {
            get
            {
                return xAxis.Accel;
            }
            set
            {
                xAxis.Accel = value;
                yAxis.Accel = value;
                zAxis.Accel = value;
            }
        }

        public float Decel
        {
            get
            {
                return xAxis.Decel;
            }
            set
            {
                xAxis.Decel = value;
                yAxis.Decel = value;
                zAxis.Decel = value;
            }
        }

        public void AllAxisesHoming()
        {
            Speed = 50;
            Accel = 200;
            Decel = 1000;
            if (allHomingMark == true)
            {
                return;
            }
            allHomingMark = true;
            zAxis.AxisHoming();
            while (zAxis.HomeStatus != AxisHomeStatus.Homed)//等待Z轴复位完成
            {
                Thread.Sleep(1);
                if (zAxis.HomeStatus == AxisHomeStatus.HomeErr)
                {
                    //Log.LogErrorMsg("Z轴回零异常。");
                    //allHomingMark = false;
                    //return;
                }
            }
            //rAxis.AxisHoming();
            //while (rAxis.HomeStatus != AxisHomeStatus.Homed)//等待r轴复位完成
            //{
            //    Thread.Sleep(1);
            //    if (rAxis.HomeStatus == AxisHomeStatus.HomeErr)
            //    {
            //        //Log.LogErrorMsg("R轴回零异常。");
            //        //allHomingMark = false;
            //        //return;
            //    }
            //}
            xAxis.AxisHoming();
            yAxis.AxisHoming();
            while (xAxis.HomeStatus != AxisHomeStatus.Homed)//等待x轴复位完成
            {
                Thread.Sleep(1);
                if (xAxis.HomeStatus == AxisHomeStatus.HomeErr)
                {
                    //Log.LogErrorMsg("R轴回零异常。");
                    //allHomingMark = false;
                    //return;
                }
            }
            while (yAxis.HomeStatus != AxisHomeStatus.Homed)//等待y轴复位完成
            {
                Thread.Sleep(1);
                if (yAxis.HomeStatus == AxisHomeStatus.HomeErr)
                {
                    //Log.LogErrorMsg("R轴回零异常。");
                    //allHomingMark = false;
                    //return;
                }
            }
            allHomingMark = false;
        }

        #endregion

        #region 插补

        public IInterpolation Interpolation { get { return interpolation; } }

        #endregion

        public void EmergentStop()
        {
            allHomingMark = false;
            motion.EmergentStop();
        }

        public void ResetEmergentStop()
        {
            motion.ResetEmergentStop();
        }

        public void Pause()
        {
            motion.Pause();
        }

        public void Resume()
        {
            motion.Resume();
        }

        public void Close()
        {
            motion.Close();
        }
    }
}
